package com.china08.yxyapi.service.mg.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.china08.yxyapi.api.manage.stu.mystudy.huixue.scoreimprove.YxyHuixuePlanCrtController.ReqModel;
import com.china08.yxyapi.api.manage.stu.mystudy.huixue.scoreimprove.YxyHuixuePlanCrtController.RespModel;
import com.china08.yxyapi.entity.db.questionbank.YxyQuesbankBookContents;
import com.china08.yxyapi.entity.db.questionbank.YxyQuesbankKnowledge;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlan;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanKnow;
import com.china08.yxyapi.repository.db.huixue.comm.YxyQuesbankBookContentsKnowledgeRepository;
import com.china08.yxyapi.repository.db.huixue.comm.YxyQuesbankBookContentsRepository;
import com.china08.yxyapi.repository.db.huixue.comm.YxyQuesbankKnowledgeRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanRepository;
import com.china08.yxyapi.service.mg.YxyHuixuePlanCrtService;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

@Service
public class YxyHuixuePlanCrtServiceImpl implements YxyHuixuePlanCrtService {
    @Autowired
    private YxyHuixuePlanRepository yxyHuixuePlanRepository;
    @Autowired
    private YxyQuesbankBookContentsRepository yxyQuesbankBookContentsRepository;
    @Autowired
    private YxyQuesbankBookContentsKnowledgeRepository yxyQuesbankBookContentsKnowledgeRepository;
    @Autowired
    private YxyQuesbankKnowledgeRepository yxyQuesbankKnowledgeRepository;
    @Autowired
    private YxyHuixuePlanKnowRepository yxyHuixuePlanKnowRepository;
    @Autowired
    private MongoTemplate mTemplate;
    List<String> list1 = new ArrayList<String>();

    @Override
    @Transactional
    public RespModel insertYxyHuixuePlan(ReqModel reqModel) {
        List<YxyHuixuePlan> planlist = yxyHuixuePlanRepository.findByStudentIdAndStatusAndSubject(reqModel.studentId, 1,
                reqModel.subject);
        RespModel respModel = new RespModel();
        if (planlist != null && planlist.size() > 0) {// 该学生存在该学科下正在进行中的学习计划
            respModel.isExistsOrNot = true;
            return respModel;
        }
        respModel.isExistsOrNot = false;
        YxyHuixuePlan entity = new YxyHuixuePlan();
        entity.setStudentId(reqModel.studentId);
        entity.setStage(reqModel.stage);
        entity.setSubject(reqModel.subject);
        entity.setSubjectName(reqModel.subjectName);
        entity.setVersionId(reqModel.versionId);
        entity.setVersionName(reqModel.versionName);
        entity.setLastScoreType(reqModel.lastScoreType);
        entity.setLastScore(reqModel.lastScore);
        entity.setSemesterId(reqModel.semesterId);
        entity.setSemesterName(reqModel.semesterName);
        entity.setBookContentId(reqModel.bookContentId);
        entity.setBookContentName(reqModel.bookContentName);
        entity.setExpectScore((reqModel.lastScore + reqModel.expectScore) > reqModel.lastScoreType
                ? (int) (reqModel.lastScoreType - reqModel.lastScore) : reqModel.expectScore);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String beginDate = sdf.format(new Date());
        entity.setBeginDate(Integer.parseInt(beginDate));
        entity.setEndDate(reqModel.endDate);
        entity.setStatus(1);
        entity.setProgress(0d);
        entity.setNotice("您的学习计划正在有条不紊的进行中，继续努力！");
        entity.setIconStatus(2);
        entity.setCurrentScore(-1d);
        yxyHuixuePlanRepository.save(entity);
        String newplanid = "";// 新添加的计划id
        String newbookContentId = "";// 新添加计划的章id
        List<YxyHuixuePlan> planlist2 = yxyHuixuePlanRepository.findByStudentIdAndStatusAndSubject(reqModel.studentId,
                1, reqModel.subject);
        if (planlist2 != null && planlist2.size() > 0) {
            YxyHuixuePlan yxyHuixuePlan = planlist2.get(0);
            newplanid = yxyHuixuePlan.getId();
            newbookContentId = yxyHuixuePlan.getBookContentId();
        }
        // 根据章id得到章下的所有节(不包括节下的小节)
        int count = 0;
        List<YxyQuesbankBookContents> contentlist = yxyQuesbankBookContentsRepository
                .findByPIdAndStatus(newbookContentId, 1);
        if (contentlist == null || contentlist.size() == 0) {// 当章下面没有节,但是有知识点时
            List<String> list2 = new ArrayList<String>();
            list2.add(newbookContentId);
            List<String> knows = yxyQuesbankBookContentsKnowledgeRepository.findKnowledgeIdByBookContentIdIn(list2);
            // 根据知识点id集合查询知识点集合
            List<YxyQuesbankKnowledge> knowledges = yxyQuesbankKnowledgeRepository
                    .findByIdInAndStatusAndIsViewOrderById(knows, 0, 1);
            for (YxyQuesbankKnowledge yxy : knowledges) {
                count++;
                YxyHuixuePlanKnow yxyHuixuePlanKnow = new YxyHuixuePlanKnow();
                String id = newplanid + yxy.getId();
                yxyHuixuePlanKnow.setPkId(id);
                yxyHuixuePlanKnow.setPlanId(newplanid);
                yxyHuixuePlanKnow.setBookContentsId(newbookContentId);
                yxyHuixuePlanKnow.setBookContentsName("第一节");
                yxyHuixuePlanKnow.setKnowId(yxy.getId());
                yxyHuixuePlanKnow.setKnowName(yxy.getName());
                yxyHuixuePlanKnow.setAttention(yxy.getStar());
                yxyHuixuePlanKnow.setProgress(0d);
                yxyHuixuePlanKnow.setOrderNum(count);
                yxyHuixuePlanKnow.setLevel(getLevel(reqModel.lastScore, reqModel.lastScoreType + 0d));
                yxyHuixuePlanKnow
                        .setGoalLevel(getLevel(
                                (reqModel.lastScore + reqModel.expectScore) > reqModel.lastScoreType
                                        ? reqModel.lastScoreType : (reqModel.lastScore + reqModel.expectScore),
                                reqModel.lastScoreType + 0d) + 1);
                yxyHuixuePlanKnowRepository.save(yxyHuixuePlanKnow);
            }
        } else {// 当章下面有节时
            for (YxyQuesbankBookContents conten : contentlist) {
                queryChild(conten);
                List<String> knows = yxyQuesbankBookContentsKnowledgeRepository.findKnowledgeIdByBookContentIdIn(list1);
                // 根据知识点id集合查询知识点集合
                List<YxyQuesbankKnowledge> knowledges = yxyQuesbankKnowledgeRepository
                        .findByIdInAndStatusAndIsViewOrderById(knows, 0, 1);

                for (YxyQuesbankKnowledge yxy : knowledges) {
                    count++;
                    YxyHuixuePlanKnow yxyHuixuePlanKnow = new YxyHuixuePlanKnow();
                    String id = newplanid + yxy.getId();
                    yxyHuixuePlanKnow.setPkId(id);
                    yxyHuixuePlanKnow.setPlanId(newplanid);
                    yxyHuixuePlanKnow.setBookContentsId(conten.getId());
                    yxyHuixuePlanKnow.setBookContentsName(conten.getName());
                    yxyHuixuePlanKnow.setKnowId(yxy.getId());
                    yxyHuixuePlanKnow.setKnowName(yxy.getName());
                    yxyHuixuePlanKnow.setAttention(yxy.getStar());
                    yxyHuixuePlanKnow.setProgress(0d);
                    yxyHuixuePlanKnow.setOrderNum(count);
                    yxyHuixuePlanKnow.setLevel(getLevel(reqModel.lastScore, reqModel.lastScoreType + 0d));
                    yxyHuixuePlanKnow.setGoalLevel(getLevel(
                            (reqModel.lastScore + reqModel.expectScore) > reqModel.lastScoreType
                                    ? reqModel.lastScoreType : (reqModel.lastScore + reqModel.expectScore),
                            reqModel.lastScoreType + 0d) + 1);
                    yxyHuixuePlanKnowRepository.save(yxyHuixuePlanKnow);
                }
                // 清空上一个节点下的知识点,准备存下一个
                list1.clear();
            }
        }
        DBCollection collection = mTemplate.getCollection(mTemplate.getCollectionName(YxyHuixuePlanKnow.class));
        DBObject dbObject = new BasicDBObject("plan_id", newplanid);
        @SuppressWarnings("rawtypes")
        List list = collection.distinct("pk_id", dbObject);
        int knowCount = list.size();
        // 修改知识点数量
        entity.setKnowCount(knowCount);

        yxyHuixuePlanRepository.save(entity);
        return respModel;
    }

    /**
     * 根据节点查询所有最终节点
     * 
     * @param contentid
     */
    public void queryChild(YxyQuesbankBookContents entity) {
        /*
         * if (entity.getIsLast() == 1) { list1.add(entity.getId()); } else {
         * List<YxyQuesbankBookContents> contentlist =
         * yxyQuesbankBookContentsRepository.findByPId(entity.getId()); for
         * (YxyQuesbankBookContents y : contentlist) { queryChild(y); } }
         */
        // 判断这个节点下有没有子节点,如果有说明是父节点,如果没有说明不是父节点
        List<YxyQuesbankBookContents> contentlist = yxyQuesbankBookContentsRepository.findByPId(entity.getId());
        if (contentlist == null || contentlist.size() == 0) {
            list1.add(entity.getId());
        } else {
            for (YxyQuesbankBookContents y : contentlist) {
                queryChild(y);
            }
        }

    }

    /**
     * 根据考试成绩和分制得到知识点级别
     * 
     * @param score
     * @param fullScore
     * @return
     */
    public Integer getLevel(Double score, Double fullScore) {
        int index = 0;
        // 筛选分数段
        for (int i = 0; i <= 10; i++) {
            if (i == 0) {
                if (score <= fullScore * 0.5) {
                    index = i;
                    break;
                }
            }
            if (i > 0) {
                if (score <= (fullScore * 0.5 + fullScore * 0.05 * i)
                        && score > (fullScore * 0.5 + fullScore * 0.05 * (i - 1))) {
                    index = i;
                    break;
                }
            }
        }
        return index;
    }
}
